import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance } from "element-plus";
import {
  PurchaseSaleContractGetAllByPagedAndSort,
  PurchaseOrdersGetAllPurchaseOrdersName,
  PurchaseOrdersUpdateContractStatus,
  GetDictionaryByDictCode
} from "@/api/stu/SupplyChainFinance";
import { FXQ } from "@/utils/public/FXQ"
import { convertCurrency } from "@/utils/transferNumberToChinese";
import { useRoute } from "vue-router";
import { ref, reactive, nextTick, watch, onMounted } from "vue";
import qs from "qs";
export function useSupplierWarehouse() {
  const route = useRoute();
  const formRef = ref<FormInstance>();
  const isSeal = ref<boolean>(false)
  const selectId = ref()
  const paymentList = ref([])
  const status = ref<boolean>(false) //判断是否是签订状态 处理生成印章以及弹窗底部
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const columns = [
    {
      label: "序号",
      type: "index",
      fixed: "left",
      minWidth: 50
    },
    {
      label: "采购项目名称",
      prop: "purchaseName",
    },
    {
      label: "采购方",
      prop: "purchaserInformation",
    },
    {
      label: "合同编号",
      prop: "contractNumber",
    },
    {
      label: "交货日期",
      prop: "deliveryDate",
    },
    {
      label: "交货地址",
      prop: "deliveryAddress",
    },
    {
      label: "总金额（元）",
      prop: "total",
    },
    {
      label: '合同状态',
      prop: "signStatus",
      cellRenderer: ({ row }) => (
        <el-tag type={
          row.contractStatus ? "success" : "warning"}>
          {
            row.contractStatus ? "已签订" : "未签订"
          }
        </el-tag>
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 140,
      slot: "operation"
    }
  ];
  const Vdialog = ref(false);
  const dataList = ref([])
  const orderList = ref()
  const loading = ref<boolean>(false);
  const contract = reactive({
    purchaseOrderId: "",
    orderInformation: "",
    contractStatus: "",
    contractNumber: "",
    contractDate: "",
    //展示的数据
    enterpriseName: '',//企业名称
    supplierName: '',//供应商名字
    year: '',
    month: '',
    day: '',
    totalMoney: '',
    totalText: '',
    deliveryDate: '',
    deliveryAdree: '',
    payMethod: '',
    payAgreement: '',
    infoList: '',
    originList: '',//后端需要获取一样的数据
  })
  //更改订单
  async function showDetail(row) {
    status.value = row.contractStatus
    contract.contractNumber = row.contractNumber
    selectId.value = row.purchaseSaleContractId
    contract.purchaseOrderId = row.purchaseName
    contract.enterpriseName = row.purchaserInformation
    contract.supplierName = row.supplyName
    contract.payMethod = row.paymentMethod
    contract.payAgreement = paymentList.value.find(a => a.dictId === row.paymentAgreement).dictName;
    contract.deliveryAdree = row.deliveryAddress
    contract.deliveryDate = row.deliveryDate.substring(0, 10)
    contract.infoList = JSON.parse(row.orderInformation)
    contract.infoList.forEach(item => {
      item.total = item.Price * item.Quantity
    })
    contract.totalMoney = row.total
    contract.totalText = row.contractAmountInWords
    contract.contractDate = row.contractDate.substring(0, 10)
    let dateArr = contract.contractDate.split(" ")[0].split("-");
    contract.year = dateArr[0];
    contract.month = dateArr[1]
    contract.day = dateArr[2]
    Vdialog.value = true
    nextTick(() => {
      const MYFXQ = FXQ.companySeal(contract.enterpriseName, 0, 0, '', '');
      let view_FQX = document.querySelector("#view_FQX");
      let MYFQX = `<img src='${MYFXQ}' style="width:100%;height:100%"  />`
      view_FQX.innerHTML = MYFQX;
      if (status.value) {
        Signet()
      }
    })
  }
  function Signet() {
    // // 生成章
    const MYFXQ = FXQ.companySeal(contract.supplierName, 0, 0, '', '');
    let view_FQX = document.querySelector("#view_FQX1");
    let MYFQX = `<img src='${MYFXQ}' style="width:100%;height:100%"  />`
    view_FQX.innerHTML = MYFQX;
    isSeal.value = true
  }

  function ClosePanelVisible() {
    for (const key in contract) {
      delete contract[key]
    }
    isSeal.value = false
    Vdialog.value = false
  }

  // 分页获取合同列表
  async function getClientBaseData() {
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
      SEIId: sessionStorage.getItem("seiId"),
    }
    const res = await PurchaseSaleContractGetAllByPagedAndSort(data);
    if (res.success) {
      res.data.items.forEach(item => {
        item.deliveryDate = item.deliveryDate.substring(0, 10)
        let total = 0
        let arr = JSON.parse(item.orderInformation)
        arr.forEach(a => {
          total = total + a.Price * a.Quantity
        })
        item.total = total
      })
      //计算商品总额
      dataList.value = res.data.items;
      pagination.total = res.data.totalCount
    } else {
      ElMessage.error(res.msg)
    }
  }
  async function getOrderList() {
    const data = qs.stringify({
      status: 1,
      taskId: route.query.taskId,
      planId: route.query.planId,
    })
    const res = await PurchaseOrdersGetAllPurchaseOrdersName(data);
    if (res.success) {
      orderList.value = res.data
    } else {
      ElMessage.error(res.msg)
    }
  }
  function ClickVdialog() {
    Vdialog.value = true;
  }

  async function addCase() {
    if (!isSeal.value) {
      ElMessage.warning("乙方未盖章")
      return
    }
    const data = qs.stringify({
      "id": selectId.value,
      "status": true,
    })
    const res = await PurchaseOrdersUpdateContractStatus(data);
    if (res.success) {
      ElMessage.success('签订购销合同成功！');
      ClosePanelVisible()
      getClientBaseData()
    } else {
      ElMessage.error(res.msg);
    }
  }
  onMounted(async () => {
    getClientBaseData()
    getOrderList()
    let data = qs.stringify({
      dictCode: 'DuePaymentDate'
    })
    const res = await GetDictionaryByDictCode(data)
    if (res.success) {
      paymentList.value = res.data
    } else {
      ElMessage.error(res.msg)
    }
  })
  function handleSizeChange() {
    getClientBaseData()
  }
  function handleCurrentChange() {
    getClientBaseData()
  }
  return {
    isSeal,
    columns,
    Vdialog,
    dataList,
    loading,
    contract,
    ClosePanelVisible,
    ClickVdialog,
    Signet,
    showDetail,
    orderList,
    addCase,
    status,
    pagination,
    handleSizeChange,
    handleCurrentChange,
  }
}
